{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7fd52743-7783-45d1-8878-b1c44434e831",
   "metadata": {},
   "source": [
    "Chapter 22\n",
    "# 鸢尾花数据帧使用apply() 自定义函数，对于特定一列\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "646e057b-c787-4380-bbef-c95602303fe8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import seaborn as sns\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b33ec22f-88d3-47f4-a0b7-a11b714f37aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "iris_df = sns.load_dataset(\"iris\")\n",
    "# 从Seaborn中导入鸢尾花数据帧\n",
    "iris_df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "895652aa-e06f-4110-9a7e-3fcbed2868b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义函数将花萼长度映射为等级\n",
    "def map_fnc(sepal_length):\n",
    "    if sepal_length < 5:\n",
    "        return 'D'\n",
    "    elif 5 <= sepal_length < 6:\n",
    "        return 'C'\n",
    "    elif 6 <= sepal_length < 7:\n",
    "        return 'B'\n",
    "    else:\n",
    "        return 'A'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "504a88fe-ee6a-49f8-9e60-e04eb54adff0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 使用 apply 函数将 sepal_length 映射为等级并添加新列\n",
    "iris_df['ctg'] = iris_df['sepal_length'].apply(map_fnc)\n",
    "iris_df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56ee4901-365a-4fc0-acf5-850a15b249ba",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
